﻿namespace Blaze.Framework
{
    using UnityEngine;
    using UnityEngine.Events;

    /// <summary>
    /// 用于监听渲染相关事件。
    /// </summary>
    public class RenderEventListener : MonoBehaviour
    {
        /// <summary>
        /// 当物体变得不可见时触发此事件。
        /// </summary>
        public UnityEvent BecameInvisible
        {
            get
            {
                if (mBecameInvisible == null)
                    mBecameInvisible = new UnityEvent();
                return mBecameInvisible;
            }
        }

        /// <summary>
        /// 当物体变得可见时触发此事件。
        /// </summary>
        public UnityEvent BecameVisible
        {
            get
            {
                if (mBecameVisible == null)
                    mBecameVisible = new UnityEvent();
                return mBecameVisible;
            }
        }

        /// <summary>
        /// 获取/创建指定对象上的<see cref="RenderEventListener"/>。
        /// </summary>
        public static RenderEventListener Get(GameObject target)
        {
            var ret = target.GetComponentInChildren<RenderEventListener>();
            if (ret == null)
            {
                var childRenderer = target.GetComponentInChildren<Renderer>();
                ret = childRenderer.gameObject.GetOrAddComponent<RenderEventListener>();
            }
            return ret;
        }

        private void OnBecameInvisible()
        {
            if (mBecameInvisible != null)
                mBecameInvisible.Invoke();
        }

        private void OnBecameVisible()
        {
            if (mBecameVisible != null)
                mBecameVisible.Invoke();
        }

        private UnityEvent mBecameInvisible;
        private UnityEvent mBecameVisible;
    }
}